<html>
<!-- canvas.drawImage() for animated images should draw the initial
  frame (or poster frame) of the animated image. -->

<body>
  <style>
    canvas { width : 315px; height: 236px; }
  </style>
  <canvas id='canvas1'></canvas>
    <img onload='loaded(this, "GIF ", 1)'><br>
  <canvas id='canvas2'></canvas>
    <img onload='loaded(this, "APNG", 2)'><br>
  <canvas id='canvas3'></canvas>
    <img onload='loaded(this, "WEBP", 3)'><br>
  <pre id='results'></pre>
</body>

<script>
if (window.testRunner) {
  testRunner.waitUntilDone();
  testRunner.dumpAsText();
}

var sources = [
  '../../images/resources/count-down-color-test.gif',
  '../../images/resources/count-down-color-test.png',
  '../../images/resources/count-down-color-test.webp',
];

function loaded(img, name, i) {
  // Advance the image away from frame 0 to a frame that has black,
  // white and gray pixels, viz., no color pixels.
  var noColorFrameDelayInMS = 1500;
  setTimeout(runTest, noColorFrameDelayInMS);

  function runTest() {
    requestAnimationFrame(function test() {
      results.textContent += name + ' image test: ';
      drawImageToCanvasTest(img, i);
      startNextTestIfNeeded(i);
    });
  }
}

function drawImageToCanvasTest(img, i) {
  var canvas = document.querySelector('#canvas' + i);
  canvas.width = img.width;
  canvas.height = img.height;

  var context = canvas.getContext('2d');
  context.drawImage(img, 0, 0);
  testImagePixel(context, img);
}

function testImagePixel(context, img) {
  var center = { x : img.width / 2, y : img.height / 2 };

  try {
    var pixel = context.getImageData(center.x, center.y, 1, 1);
  } catch (exception) {
    results.textContent += 'FAIL: ' + exception + '\n';
    return;
  }

  // Frame 0 has color pixels: PASS if the center pixel is ~green.
  var green =
    pixel.data[0] < 5 && pixel.data[1] > 180 && pixel.data[2] < 5;
  results.textContent += green ? 'PASS\n' : 'FAIL\n';
}

function startNextTestIfNeeded(i) {
  if (i < sources.length) {
    document.querySelectorAll('img')[i].src = sources[i];
  } else if (window.testRunner) {
    testRunner.notifyDone();
  }
}

startNextTestIfNeeded(0);
</script>
</html>
